<?php
namespace app\logic;


use think\facade\Cookie;
use think\facade\Session;

class User extends Base
{
    // 初始化
    protected function initialize()
    {
        parent::initialize();

        $this->model = new \app\model\User();
    }

    /**
     * 生成 remember_token
     * @return string
     */
    protected function setToken()
    {
        $str = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $token = "";
        for($i = 0; $i < 10; $i++) {
            $token .= substr($str, rand(0, strlen($str)), 1);
        }
        
        return $token;
    }

    /**
     * 登录逻辑
     * @param array $param
     * @return array
     */
    public function login(array $param = [])
    {
        $user = $this->model->getOneInfoByWhere([
            ['username', '=', $param['username']],
            ['password', '=', md5($param['password'])]
        ]);
        if($user->isEmpty()) {
            return [config('status.verify'), '登录信息不存在或不匹配'];
        }
        $token = $this->setToken();
        Session::set('user', [
            'id'    => $user->id,
            'token' => $token
        ]);
        if(isset($param['remember'])) {
            // 保存七天
            Cookie::set('user', aes_encrypt($user->id .'@@@'. $token), 7*24*60*60);
        } else {
            Cookie::set('user', aes_encrypt($user->id .'@@@'. $token), null);
        }
        // 更新数据
        $user->token        = $token;
        $user->last_time    = date('Y-m-d', time());
        $user->last_ip      = request()->ip();
        $user->save();

        return [config('status.success'), '登录成功', [], (string) url('Index/index')];
    }

    /**
     * 判断是否登录
     * @return bool
     */
    public function isLogin()
    {
        $session_user = Session::get('user');
        $cookie_user = Cookie::get('user');
        // session/cookie 都不存在
        if(!$session_user && !$cookie_user) return false;
        // 判断 session 是否存在
        if(!$session_user) {
            $user = explode('@@@', aes_decrypt($cookie_user));
            // 信息不匹配
            if(!$user[1]) return false;
            $get_user = $this->model->getOneInfoByWhere([
                ['id', '=', $user[0]],
                ['token', '=', $user[1]]
            ]);
            // id/token 不存在
            if (!$get_user) return false;
            Session::set('user', [
                'id'    => $get_user->id,
                'token' => $get_user->token
            ]);
            return true;
        }
        // 判断 cookie 是否存在
        if(!$cookie_user) {
            $get_user = $this->model->getOneInfoByWhere([
                ['id', '=', $session_user['id']],
                ['token', '=', $session_user['token']]
            ]);
            // id/token 不存在
            if (!$get_user) return false;
            Cookie::set('user', aes_encrypt($get_user->id .'@@@'. $get_user->token), null);
            return true;
        }

        return true;
    }

    /**
     * 退出登录
     * @return array
     */
    public function logout()
    {
        if($this->isLogin()) {
            $session_user = Session::get('user');
            $get_user = $this->model->getOneInfoByWhere([
                ['id', '=', $session_user['id']],
                ['token', '=', $session_user['token']]
            ]);
            if($get_user) {
                // 删除 token
                $get_user->token = "";
                $get_user->save();
            }
            Session::delete("user");
            Cookie::delete("user");
        }

        return [config('status.success'), "退出登录成功", [], (string) url('login/index')];
    }

    /**
     * 修改个人资料
     * @param $param
     * @return array
     */
    public function profile($param)
    {
        $id = session('user')['id'] ?? 0;
        $user = $this->model->getOneInfoByWhere(['id' => $id]);
        if($user->isEmpty()) {
            return [config('status.fail'), "可能未完成登录"];
        }
        // 是否需要修改密码
        if(!empty($param['password'])) {
            // 验证旧密码
            if($user->password !== md5($param['old_password'])) {
                return [config('status.verify'), "旧密码验证错误"];
            }
            // 修改密码且重置秘钥
            $user->password = md5($param['password']);
            $user->token = "";
        }
        // 修改用户名
        $user->username = $param['username'];
        $result = $user->save();
        if($result) {
            return [config('status.success'), "信息修改成功"];
        }
        return [config('status.fail'), "信息修改失败"];
    }
}